//
//  HELOrderConfirmVC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/3/6.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "HELOrderConfirmVC.h"
#import "HELPayMethondConfirmVC.h"
#import "DGSAttributedStringSuite.h"
#import "UIImageView+BTimageView.h"
#import "HELOrderModel.h"
#import "HELCouponModel.h"
#import "HELCouponVC.h"
#import "PayHtm5VC.h"

@interface HELOrderConfirmVC ()
@property (weak, nonatomic) IBOutlet UIImageView *courseImg;
@property (weak, nonatomic) IBOutlet UILabel *DesL;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;

@property (weak, nonatomic) IBOutlet UILabel *courseNameL;

@property (weak, nonatomic) IBOutlet UILabel *duePriceL;

@property (weak, nonatomic) IBOutlet UIButton *couponBtn;

@property (weak, nonatomic) IBOutlet UILabel *coursePriceL;

@property (nonatomic,  strong) HELOrderModel *order;
@property (weak, nonatomic) IBOutlet UILabel *courseNameL2;
@property (weak, nonatomic) IBOutlet UILabel *couponPriceBtn;
@property (weak, nonatomic) IBOutlet UILabel *finalPriceDesL;
@property (weak, nonatomic) IBOutlet UILabel *realPriceL;



@property (weak, nonatomic) IBOutlet UILabel *subimit_price;

@property (weak, nonatomic) IBOutlet UILabel *submit_hasCcountL;
@property (weak, nonatomic) IBOutlet UILabel *statusL;

@property (nonatomic,  strong) NSMutableArray *couponArray;


//默认 -1   用户选择不用 则 -2
@property (nonatomic,  assign) NSInteger selectedCouponIndex;

@property (nonatomic,  strong)  NSNumber *final_price;

@property (nonatomic,  strong)  NSNumber *discounted_price;




@end

@implementation HELOrderConfirmVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"确认订单";
    self.selectedCouponIndex = -1;
    [self createOrder];
}


- (NSMutableArray *)couponArray{
    if (!_couponArray) {
        _couponArray =[NSMutableArray array];
    }
    return _couponArray;
}


- (IBAction)confirmOrder:(id)sender {
    
    [self confirmOrder];
    
    
    
}



//创建订单
- (void)createOrder{
    
    
    [self wsj_showLodingGif];
    weakSelf_define;
    [[HELNetworkManager sharedMg] POST:helCreateOrder parameters:@{@"courseId":@(self.courseId)} success:^(id responseObject) {
      
        
        if (![responseObject[@"success"] isKindOfClass:[NSNull class]]  &&  [responseObject[@"success"] integerValue] == 1) {
          
            [weakSelf getOrderWith:responseObject[@"data"]];
        }else{
            [weakSelf wsj_hideLodingGif];
            [weakSelf wsj_showLoadFailviewWithRetry:^{
                [weakSelf createOrder];
            }];
        
        }
     
        
    } failure:^(NSString *err) {
        [weakSelf wsj_hideLodingGif];
        [weakSelf wsj_showLoadFailviewWithRetry:^{
            [weakSelf createOrder];
        }];
    }];

}


//预览订单
- (void)getOrderWith:(NSString *)str{
   
    
    weakSelf_define;
   
  
    [[HELNetworkManager sharedMg] GET:[NSString stringWithFormat:@"%@/%@",helPreviewOrder,str] parameters:nil success:^(id responseObject) {
       [weakSelf wsj_hideLodingGif];
        if (![responseObject[@"success"] isKindOfClass:[NSNull class]]  &&  [responseObject[@"success"] integerValue] == 1) {
           
            weakSelf.order = [HELOrderModel mj_objectWithKeyValues:responseObject[@"data"][@"order"]];
            NSArray *tem_arr =responseObject[@"data"][@"couponList"];
            if ([tem_arr isKindOfClass:[NSArray class]]) {
                [weakSelf.couponArray removeAllObjects];
                [tem_arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
                    [dic addEntriesFromDictionary:obj[@"couponMember"]];
                    [dic addEntriesFromDictionary:obj[@"couponActivityIntro"]];
                    
                    [weakSelf.couponArray addObject:[HELCouponModel mj_objectWithKeyValues:dic]];
                }];
                
            }
            weakSelf.final_price =@([weakSelf.order.amountPay doubleValue]);
            weakSelf.discounted_price = @(0);
            [weakSelf reFreshUI];
        }else{
            [weakSelf wsj_showLoadFailviewWithRetry:^{
                [weakSelf createOrder];
            }];
        }
        
        
    } failure:^(NSString *err) {
    [weakSelf wsj_hideLodingGif];
    [weakSelf wsj_showLoadFailviewWithRetry:^{
        [weakSelf createOrder];
    }];
    }];
    
}




- (void)getFinalPriceAfterUseCoupon:(NSInteger)couponId{

    
    NSString *url =[NSString  stringWithFormat:@"%@/%@/%@",helGetPriceuserCoupon,self.order.id,@(couponId)];
    [self wsj_showLodingGif];
    weakSelf_define;
   [[HELNetworkManager sharedMg] GET:url parameters:nil success:^(id responseObject) {
       [weakSelf wsj_hideLodingGif];
       weakSelf.final_price = responseObject[@"data"][@"postpaymentAmount"];
       weakSelf.discounted_price = responseObject[@"data"][@"discountedPrice"];
       [weakSelf reFreshUI];
   } failure:^(NSString *err) {
       [weakSelf wsj_hideLodingGif];
      
       
   }];

}

//提交订单

- (void)confirmOrder{


    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    cwqHud(self.view);
    if (self.selectedCouponIndex >=0) {
       
        HELCouponModel *model = self.couponArray[self.selectedCouponIndex];
        params[@"couponId"] = model.id;
        params[@"amountPay"] = self.final_price;
    }

    weakSelf_define;
   [[HELNetworkManager sharedMg] POST:[NSString stringWithFormat:@"%@/%@",helConfirmOrder,self.order.id] parameters:params success:^(id responseObject) {
        [hud hide:YES];
       if (![responseObject[@"success"] isKindOfClass:[NSNull class]] && [responseObject[@"success"] integerValue]) {
           HELPayMethondConfirmVC *vc = [HELPayMethondConfirmVC new];
           
//           vc.orderId = weakSelf.order.id;
//           vc.price = [weakSelf.final_price doubleValue];
//           [weakSelf.navigationController pushViewController:vc animated:YES];
//           
          
           //调用 h5
           PayHtm5VC *payVC = [[PayHtm5VC alloc] init];
           NSString *url ;
//           url = [NSString stringWithFormat:@"%@/%@/%@", [HELNetworkManager sharedMg].bathURL,helPayHtml5,weakSelf.order.id];
           url = [NSString stringWithFormat:@"%@/%@/ios/%@",[HELNetworkManager sharedMg].bathURL,helGetOrderString,self.order.id];
           payVC.theUrl = [NSURL URLWithString:url];
           payVC.needToken = YES;
           payVC.title = @"支付界面";
           [weakSelf.navigationController pushViewController:payVC animated:YES];
           
           
       }
       
   } failure:^(NSString *err) {
        [hud hide:YES];
   }];

}



- (void)reFreshUI{
    
    if (!self.order) {
        return;
    }
   
    NSString *str1 = @"特别提示:";
    NSString *str2 = @"本次购买的课程仅属于当年有效的学分课程，请认真查看课程的有效时间,合理安排学习时间";
    
    NSMutableAttributedString *attStr = [NSMutableAttributedString dgs_makeString:^(DGSAttributedStringMaker *add)
                               {
                                   add.string(str1).with.
                                   color([UIColor redColor]).
                                   strikedThroughWithStyle(NSUnderlineStyleNone);
                                   add.string(str2).
                                   underlinedWithStyle(NSUnderlineStyleNone)
                                   .color([UIColor blackColor]);
                               }];
    self.DesL.attributedText = attStr;
    
    self.courseNameL.text= self.order.courseName;
    
//    self.order_tag.text = @"永久有效";
  
    
    self.duePriceL.text = [NSString stringWithFormat:@"¥%@.00",self.order.amountDue];
   
    if (self.couponArray.count>0) {
      
        //选了 优惠券
        
        if (self.selectedCouponIndex >=0) {
            HELCouponModel *coupon = self.couponArray[self.selectedCouponIndex];
            [self.couponBtn setTitle:coupon.title forState:UIControlStateNormal];
            self.couponPriceBtn.text = [NSString stringWithFormat:@"-¥%.2f",[self.discounted_price doubleValue]];
            self.finalPriceDesL.text = [NSString stringWithFormat:@"总计¥%.2f  已优惠¥%.2f", [self.final_price doubleValue],[self.discounted_price doubleValue]];
             self.realPriceL.text = [NSString stringWithFormat:@"¥%.2f",[self.final_price doubleValue]];
             self.submit_hasCcountL.text = [NSString stringWithFormat:@"已优惠(¥%.2f)",[self.discounted_price doubleValue]];
            [self.couponBtn setTitleColor:kPinchColor forState:UIControlStateNormal];
              self.subimit_price.text = [NSString stringWithFormat:@"¥%.2f",[self.final_price doubleValue]];
        }else{
            self.subimit_price.text = [NSString stringWithFormat:@"¥%.2f",[self.order.amountDue doubleValue]];
             self.couponPriceBtn.text = @"不使用优惠券";
            if (self.selectedCouponIndex == -2) {
                 [self.couponBtn setTitle:[NSString stringWithFormat:@"不使用"] forState:UIControlStateNormal];
                
                 [self.couponBtn setTitleColor:kTxtColor forState:UIControlStateNormal];
            }else{  //-1
                [self.couponBtn setTitle:[NSString stringWithFormat:@"%@张可用",@(self.couponArray.count)] forState:UIControlStateNormal];
                self.couponPriceBtn.text = [NSString stringWithFormat:@"¥0.00"];
                self.finalPriceDesL.text = [NSString stringWithFormat:@"总计¥%@  已优惠¥0.00",self.order.amountPay?self.order.amountPay:@"0.00"];
                self.realPriceL.text = [NSString stringWithFormat:@"¥%.2f",[self.final_price doubleValue]];
                self.submit_hasCcountL.text = [NSString stringWithFormat:@"已优惠(¥0.00)"];
                [self.couponBtn setTitleColor:kPinchColor forState:UIControlStateNormal];
                
            }
   
        }
    }else{
     
        self.subimit_price.text = [NSString stringWithFormat:@"¥%.2f",[self.order.amountDue doubleValue]];
        [self.couponBtn setTitle:[NSString stringWithFormat:@"无可用优惠券"] forState:UIControlStateNormal];
        self.couponBtn.enabled  =NO;
           [self.couponBtn setTitleColor:kTxtColor forState:UIControlStateNormal];
       self.couponPriceBtn.text = @"不使用优惠券";
        self.finalPriceDesL.text = [NSString stringWithFormat:@"总计¥%.2f  已优惠¥0.00",[self.final_price doubleValue]];
       
        self.realPriceL.text = [NSString stringWithFormat:@"¥%.2f",[self.final_price doubleValue]];
        
    }
     self.submit_hasCcountL.text = [NSString stringWithFormat:@"已优惠(%.2f)",[self.discounted_price doubleValue]];
    self.statusL.text = self.order.statusDesc;
    self.courseNameL2.text = self.order.courseName;
    self.coursePriceL.text = [NSString stringWithFormat:@"¥%@.00",self.order.amountDue];
 
    [self.courseImg nc_setImageWithUrl:self.order.courseImage];
  
    if (![self.order.status containsString:@"待确认"]) {
        self.commitBtn.enabled = YES;
        
    }else{
        self.commitBtn.enabled = NO;
        [self.commitBtn setBackgroundColor:[UIColor lightGrayColor]];
    }
    
    //amountDue = 23; //应付
    //amountPay = 23; //实付
    //couponId = "<null>";
    //courseId = 318;
    //courseName = testttt;
    //createTime = 1488878319000;
    //id = 2017030717183947670;
    //outTradeNo = "<null>";
    //payType = "<null>";
    //status = "order_confirm";
    //statusDesc = "\U5f85\U786e\U8ba4";
    //updateTime = 1488878319000;
    //userId = 200831002067;

 

}
- (IBAction)chooseCouponsAction:(id)sender {
    
    HELCouponVC *vc =[HELCouponVC new];
    vc.coupons_arr = self.couponArray;
    weakSelf_define;
    vc.callBack = ^(NSInteger index){
        
        weakSelf.selectedCouponIndex = index;
      
        if (index>=0) {
              HELCouponModel *model = weakSelf.couponArray[index];
            [weakSelf getFinalPriceAfterUseCoupon:[model.id integerValue]];
        }else{
            
            weakSelf.final_price = @([weakSelf.order.amountPay doubleValue]);
            weakSelf.discounted_price = @(0);
          [weakSelf reFreshUI];
        }
      
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

@end
